package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.qo.JSONResult;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    //查询部门请求
    @RequestMapping("/list")
    public String list(Model model, EmployeeQueryObject qo){

        PageResult<Role> pageResult = roleService.query(qo);
        model.addAttribute("pageResult", pageResult);
        model.addAttribute("qo", qo);
        return "role/list";
    }
    //处理删除部门请求
    @RequestMapping("/delete")
    @ResponseBody
    public JSONResult delete(Long id){

        try {


            roleService.delete(id);
            return new JSONResult();

        } catch(Exception e) {
            e.printStackTrace();

            //在PageResult中添加构造器的注解
            return new JSONResult(false,"错误");
        }

    }

    //处理新增部门信息
    @RequestMapping("/input")
    public String input(Long id,Model model){

        if (id != null) {
            Role role = roleService.get(id);
            model.addAttribute("role", role);


        }
        List<Permission> permissions = permissionService.listALL();
        model.addAttribute("permissions", permissions);

        return "role/input";
    }

    //处理新增和修改页面
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role,Long[] ids){

        if (role.getId() != null) {

            roleService.update(role,ids);
        }else {
            roleService.save(role,ids);

        }
        return "redirect:/role/list.do";
    }
}
